package com.vca.common.utils;

import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class WechatGenerateUrl {

    public static String getURLScheme(String apiUrl, String query, String pageUrl) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> m = new HashMap<>();
        String page = pageUrl.substring(0, pageUrl.indexOf("?"));
        String queryString = pageUrl.substring(pageUrl.indexOf("?") + 1, pageUrl.length());
        m.put("path", page);
        m.put("query", queryString);
        map.put("jump_wxa", m);
        String requestBody = JSONObject.toJSONString(map);
        URL url = new URL(apiUrl + "?" + query);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        connection.getOutputStream().write(requestBody.getBytes(StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();
        connection.disconnect();
        return builder.toString();
    }
}
